from django.shortcuts import render
from django.template import RequestContext
from django.shortcuts import render_to_response
from django.contrib.auth import authenticate, login
from django.http import HttpResponseRedirect, HttpResponse
from django.contrib.auth import logout
from Reservation.forms import UserForm, UserProfileForm, SearchForm
from Reservation.models import *
from datetime import date,datetime
from django.db.models import Q

def index(request):
    context = RequestContext(request)
    Offer = HotelRoomsInOffer.objects.filter().order_by('-id')[:3]
    search_form=SearchForm()
    context_dict = {'latestoffers': Offer, 'searchform':search_form}
    return render_to_response('Reservation/index.html', context_dict, context)

def search(request):
    context = RequestContext(request)
    if request.method == 'POST':
        destination = request.POST['Destination']
        hotelname = request.POST['HotelName']
        checkindate = request.POST['CheckInDate']
        checkOutDate= request.POST['CheckOutDate']
        now = datetime.now()
        date_now = now.strftime("%Y-%m-%d")
        if checkOutDate < checkindate:
            return HttpResponseRedirect('/Reservation/')
        if checkindate < date_now:
            return HttpResponseRedirect('/Reservation/')
        chindate = datetime.strptime(checkindate, '%Y-%m-%d')
        choutdate = datetime.strptime(checkOutDate, '%Y-%m-%d')
        days = (choutdate-chindate).days
        if destination and hotelname and checkindate and checkOutDate:
            offers=Offer.objects.filter(Q(hotel__Name__icontains=hotelname),Q(hotel__Country__icontains=destination),Q(offer_start__gte=checkindate),Q(offer_end__lte=choutdate))
        elif destination and checkindate and checkOutDate:
            offers=Offer.objects.filter(Q(hotel__Country__icontains=destination),Q(offer_start__gte=checkindate),Q(offer_end__lte=choutdate))
        else:
            offers=Offer.objects.filter(Q(hotel__Name__icontains=hotelname),Q(offer_start__gte=checkindate),Q(offer_end__lte=choutdate))
        request.session['days']=days
        context_dict = {'offers': offers, 'days':days}
        return render_to_response('Reservation/searchresult.html', context_dict, context)
    else:
        search_form = SearchForm()
        return render_to_response('Reservation/Search.html', {'search_form': search_form}, context)

def offer(request):
    context=RequestContext(request)
    Offer = HotelRoomsInOffer.objects.select_related().order_by('-id')
    context_dict = {'offers': Offer}
    return render_to_response('Reservation/offers.html', context_dict, context)



def offerinfo(request,offer_id):
    context=RequestContext(request)
    offer=HotelRoomsInOffer.objects.select_related('room').filter(id=offer_id)
    for x in offer:
        comments=HotelComment.objects.filter(hotel=x.room.hotel.id,offer=x.offer.id)
    context_dict={'offer': offer,'comment':comments}
    return render_to_response('Reservation/offerinfo.html',context_dict , context)

def book(request):
    context=RequestContext(request)
    if 'user_id' in request.session:
        if request.method == 'POST':
            uid=request.session['user_id']
            checkin = request.POST['checkin']
            checkout= request.POST['checkout']
            roomid=request.POST['room']
            offerid=request.POST['offer']
            now = datetime.now()
            datenow = now.strftime("%Y-%m-%d")
            if checkout < checkin:
                return HttpResponseRedirect(request.META.get('HTTP_REFERER'))
            if checkin < datenow:
                return HttpResponseRedirect(request.META.get('HTTP_REFERER'))
            chkin = datetime.strptime(checkin, '%Y-%m-%d')
            chkout = datetime.strptime(checkout, '%Y-%m-%d')
            days = (chkout-chkin).days
            record=HotelRoomsInOffer.objects.select_related('room').get(offer_id=offerid,room_id=roomid)
            BookedRoom=UserBooking(user_id=uid,startdate=chkin,enddate=chkout,offer_id=offerid)
            BookedRoom.save()
            totalprice=(record.offer.offer_discount) * days
            context_dict={'price':totalprice,'offers':record}
            return render_to_response('Reservation/bookcost.html',context_dict , context)
    else:
        return HttpResponseRedirect('/Reservation/login')

def comment(request):
    context=RequestContext(request)
    if 'user_id' in request.session:
         if request.method == 'POST':
             uid=request.session['user_id']
             coment = request.POST['comment']
             hotelid=request.POST['hotel']
             offerid=request.POST['offer']
             print hotelid
             print offerid
             com = HotelComment(body=coment, hotel_id=hotelid,offer_id=offerid,user_id=uid)
             com.save()
             comments=HotelComment.objects.filter(hotel=hotelid)
             offer=HotelRoomsInOffer.objects.select_related('room').filter(id=offerid)
             context_dict={'offer': offer,'comment':comments}
             return HttpResponseRedirect(request.META.get('HTTP_REFERER'))
    else:
        return HttpResponseRedirect('/Reservation/login')


def register(request):

    context = RequestContext(request)
    registered = False
    if request.method == 'POST':
        user_form = UserForm(data=request.POST)
        profile_form = UserProfileForm(data=request.POST)
        if user_form.is_valid() and profile_form.is_valid():

            user = user_form.save()
            user.set_password(user.password)
            user.save()
            profile = profile_form.save(commit=False)
            profile.user = user
            if 'picture' in request.FILES:
                profile.picture = request.FILES['picture']
            profile.save()
            registered = True
        else:
            print user_form.errors, profile_form.errors
    else:
        user_form = UserForm()
        profile_form = UserProfileForm()
    return render_to_response(
        'Reservation/register.html',
        {'user_form': user_form, 'profile_form': profile_form, 'registered': registered},
        context)

def user_login(request):
    context = RequestContext(request)
    if request.method == 'POST':
        username = request.POST['username']
        password = request.POST['password']
        user = authenticate(username=username, password=password)
        if user is not None:
            if user.is_active:
                login(request, user)
                userdata=User.objects.filter(username=username)
                if userdata is not None:
                    for u in userdata:
                        request.session['user_id']=u.id
                request.session['user_name']=username
                return HttpResponseRedirect('/Reservation/')
            else:
                return HttpResponse("Your account is disabled.")
        else:
            print "Invalid login details: {0}, {1}".format(username, password)
            return HttpResponseRedirect('/Reservation/login')
    else:
        return render_to_response('Reservation/login.html', {}, context)

def user_logout(request):
    logout(request)
    return HttpResponseRedirect('/Reservation/')

# Create your views here.
